<template>
    <van-popup v-model="showPop">
        <div class="con">
            <van-field v-model="code" :label="label" center clearable placeholder="请输入短信验证码">
                <template #button>
                    <van-button size="small" type="info" :disabled="!!timer || isLoading" :loading="isLoading" @click="countDownAction" style="width:80px">{{showText}}</van-button>
                </template>
            </van-field>
            <div class="butt">
                <van-button type="info" size="large" @click="nextStep">提交</van-button>
            </div>
        </div>
    </van-popup>
</template>

<script>


export default {
    props: ['label'],
    inject: ['sendCode'],

    data() {
        return {
            showPop: false,
            code: "",
            timer: null,
            sec: 0,
            isLoading: false,
        }
    },

    destroyed() {
        clearInterval(this.timer);
        this.timer = null;
    },

    computed: {
        // 格式化读秒显示
        formateSec() {
            if (this.sec >= 10) {
                return `${this.sec}`
            } else {
                return `0${this.sec}`
            }
        },

        // 整合界面显示文案
        showText() {
            if (this.timer) {
                return `还剩${this.formateSec}秒`
            } else {
                return "获取验证码"
            }
        }
    },

    methods: {
        show() {
            this.showPop = true
        },

        // 提交
        nextStep() {
            this.$emit("commit", this.code);
        },

        // 点击倒计时按钮
        countDownAction() {
            if (this.timer || this.isLoading) {
                return
            }
            this.isLoading = true;
            this.sendCode().then((ret) => {
                this.startCountDown(ret)
            })
        },

        // 开始倒计时
        startCountDown(sendFlag = true) {
            this.isLoading = false;
            if (sendFlag === false) {
                return;
            }
            this.sec = SEC;
            // 开始倒计时
            this.timer = setInterval(() => {
                this.sec--;
                if (this.sec == 0) {
                    this.resetStatus();
                }
            }, 1000);
        },

        // 重置样式
        resetStatus() {
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null
            }
            this.sec = SEC;
        },
    }
}
</script>

<style lang="scss" scoped>
.con {
    width: 340px;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 40px 20px;

    .butt {
        margin-top: 20px;
    }
}

.van-popup {
    background-color: inherit;
}
</style>